angular.module('starter.services', [])

.factory('Chats', function() {
  // Might use a resource here that returns a JSON array

  // Some fake testing data
  var chats = [{
    id: 0,
    name: 'Ben Sparrow',
    lastText: 'You on your way?',
    face: 'img/ben.png'
  }, {
    id: 1,
    name: 'Max Lynx',
    lastText: 'Hey, it\'s me',
    face: 'img/max.png'
  }, {
    id: 2,
    name: 'Adam Bradleyson',
    lastText: 'I should buy a boat',
    face: 'img/adam.jpg'
  }, {
    id: 3,
    name: 'Perry Governor',
    lastText: 'Look at my mukluks!',
    face: 'img/perry.png'
  }, {
    id: 4,
    name: 'Mike Harrington',
    lastText: 'This is wicked good ice cream.',
    face: 'img/mike.png'
  }];

  return {
    all: function() {
      return chats;
    },
    remove: function(chat) {
      chats.splice(chats.indexOf(chat), 1);
    },
    get: function(chatId) {
      for (var i = 0; i < chats.length; i++) {
        if (chats[i].id === parseInt(chatId)) {
          return chats[i];
        }
      }
      return null;
    }
  };
})
.factory('timeoutHttpIntercept', function ($rootScope, $q) {
  return {
    'request': function(config) {
      config.timeout = 15000;
      return config;
    }
  };
})
.service("GetData",function($q, $http,RSA,CONSTANT) {
    return {
      /*
       post请求 带加密
       */
      postRequest:function(api,param){
        var deferred = $q.defer();
        var promise = deferred.promise;
        var lyb=3;
        if(!CONSTANT.is_ios)
        {
          lyb=1;
        }
        RSA.mixByPubic(JSON.stringify(param)).success(function (data) {
          //data=encodeURIComponent(data);
          $http({
            method: 'POST',
            url: api,
            params: {jsonStr:data,lybs:lyb},
            transformResponse: [function (data, headers) {
              return data;
            }]
          }). success(function(data, status, headers, config)
            {
              RSA.backmixByPublic(data)
                .success(function (data) {
                  if(data==null||data=='')
                  {
                    deferred.reject("error");
                  }
                  else
                  {
                    try
                    {
                      var obj_d=JSON.parse(data);
                      deferred.resolve(obj_d)
                    }catch(e)
                    {
                      deferred.reject("error");
                    }
                  }
                })
                .error(function (error) {deferred.reject(error); });
            })
            . error(function(data, status, headers, config) {deferred.reject(data); });
        }).error(function (error) {deferred.reject(error); });
        promise.success = function(fn) {
          promise.then(fn);
          return promise;
        }
        promise.error = function(fn) {
          promise.then(null, fn);
          return promise;
        }
        return promise;
      },
      /*
       get请求 带加密
       */
      getRequest:function(api,param){
        var deferred = $q.defer();
        var promise = deferred.promise;
        var lyb=3;
        if(!CONSTANT.is_ios)
        {
          lyb=1;
        }
        RSA.mixByPubic(JSON.stringify(param)).success(function (data) {
          $http({
            method: 'GET',
            url: api,
            params: {jsonStr:data,lybs:lyb},
            transformResponse: [function (data, headers) {
              return data;
            }]
          }). success(function(data, status, headers, config)
          {
            RSA.backmixByPublic(data)
              .success(function (data) {
                if(data==null||data=='')
                {
                  deferred.reject("error");
                }
                else
                {
                  try
                  {
                    var obj_d=JSON.parse(data);
                    deferred.resolve(obj_d)
                  }catch(e)
                  {
                    deferred.reject("error");
                  }
                }
              })
              .error(function (error) { deferred.reject(error); });
          }).
          error(function(data, status, headers, config) {deferred.reject(data); });
        }).error(function (error) {
          deferred.reject(error);
        });
        promise.success = function(fn) {
          promise.then(fn);
          return promise;
        }
        promise.error = function(fn) {
          promise.then(null, fn);
          return promise;
        }
        return promise;
      }
    }
  })
.factory('RSA', function($q,CONSTANT){
    return {
      mixByPubic:function(tag){
        var deferred = $q.defer();
        var promise = deferred.promise;
        if(CONSTANT.IS_JM==false||CONSTANT.is_ios)
        {
          deferred.resolve(tag);
        }
        else {
          window.plugins.PluginRsa.mixbypublic(tag,
            function (success) {deferred.resolve(success);},
            function (fail) {deferred.reject(fail); });
        }
        promise.success = function(fn) {
          promise.then(fn);
          return promise;
        }
        promise.error = function(fn) {
          promise.then(null, fn);
          return promise;
        }
        return promise;
      },
      backmixByPravate:function(tag){
        var deferred = $q.defer();
        var promise = deferred.promise;
        if(CONSTANT.IS_JM==false||CONSTANT.is_ios)
        {
          deferred.resolve(tag);
        }
        else {
          window.plugins.PluginRsa.backmixbyprivate(tag,
            function (success) { deferred.resolve(success); },
            function (fail) {deferred.reject(fail); });
        }
        promise.success = function(fn) {
          promise.then(fn);
          return promise;
        }
        promise.error = function(fn) {
          promise.then(null, fn);
          return promise;
        }
        return promise;
      },
      backmixByPublic:function(tag){
        var deferred = $q.defer();
        var promise = deferred.promise
        if(CONSTANT.IS_JM==false||CONSTANT.is_ios)
        {
          deferred.resolve(tag);
        }
        else {
          window.plugins.PluginRsa.backmixbypublic(tag,
            function (success) {deferred.resolve(success);},
            function (fail) {deferred.reject(fail); });
        }
        promise.success = function(fn) {
          promise.then(fn);
          return promise;
        }
        promise.error = function(fn) {
          promise.then(null, fn);
          return promise;
        }
        return promise;
      }
    };
  })
.service("VERSION",function($cordovaPreferences,CONSTANT,makeHeadParam,GetData,$cordovaToast,$ionicLoading,$cordovaAppVersion, $ionicPopup,$cordovaFileTransfer,$timeout, $cordovaFileOpener2){
    return {
      getVersion:function(istoast){
        if(istoast)
        {
          $ionicLoading.show({
            template: '<ion-spinner icon="lines" class="spinner-balanced"></ion-spinner><p>获取版本信息中</p>'
          });
        }
        $cordovaPreferences.fetch(CONSTANT.tokenKey)
          .success(function (token) {
            $cordovaAppVersion.getVersionNumber().then(function (version_num) {
              $cordovaAppVersion.getVersionCode().then(function (version_code) {
                var cash_param = makeHeadParam.getVersionInfoParameter(token, version_code);
                var url_uniform = CONSTANT.url + CONSTANT.url_uniform;
                var apk_uniform = CONSTANT.url + CONSTANT.apk_url;
                /*alert(JSON.stringify(cash_param));
                 alert(url_uniform);
                 alert(apk_uniform);*/
                GetData.postRequest(url_uniform, cash_param).success(function (re) {
                  $ionicLoading.hide();
                  if (re != null && re != '') {
                    if (re.returncode == '1000') {
                      if(istoast)
                      {
                        $cordovaToast.show('有新版本', 'long', 'bottom');
                      }
                      //alert(JSON.stringify(re.message));
                      if(CONSTANT.is_ios==false){
                        showUpdateConfirm_android(apk_uniform,re.message,version_code,version_num,re.message.bbh);
                      }
                      else {
                        showUpdateConfirm_ios(re.message,version_num,re.message.bbh);
                      }
                    }
                    else {
                      if(istoast)
                      {
                        $cordovaToast.show('当前为最新版本', 'long', 'bottom');
                      }
                    }
                  }
                }).error(function (data) {
                  $ionicLoading.hide();
                  if(istoast)
                  {
                    $cordovaToast.show('获取版本信息失败', 'long', 'bottom');
                  }
                });
              });
            });
          }).error(function (error) {
          $ionicLoading.hide();
          if(istoast)
          {
            $cordovaToast.show('本地token获取失败', 'long', 'bottom');
          }
        });
      }
    }
    checkUpdate = function () {
      var serverAppVersion = "1.0.1"; //从服务端获取最新版本
      //获取版本
      $cordovaAppVersion.getVersionNumber().then(function (version) {
        //如果本地与服务端的APP版本不符合
        if (version != serverAppVersion) {
          showUpdateConfirm(serverAppVersion);
        }
      });
    };
    function showUpdateConfirm_android(apk_uniform,obj,version,num1,num2) {
      var confirmPopup = $ionicPopup.confirm({
        title: '版本升级:' + num1+' - '+num2,
        template: obj.gxnr, //从服务端获取更新的内容
        cancelText: '取消',
        okText: '升级'
      });
      confirmPopup.then(function (res) {
        if (res) {
          $ionicLoading.show({
            template: "已经下载：0%"
          });
          var url = apk_uniform+"?objDispidx="+version; //可以从服务端获取更新APP的路径
          var targetPath = cordova.file.externalApplicationStorageDirectory+'spZone.apk'; //APP下载存放的路径，可以使用cordova file插件进行相关配置
          var trustHosts = true
          var options = {};
          //alert(cordova.file.externalApplicationStorageDirectory+'spZone.apk');
          $cordovaFileTransfer.download(url, targetPath, options, trustHosts).then(function (result) {
            // 打开下载下来的APP
            $cordovaFileOpener2.open(targetPath, 'application/vnd.android.package-archive'
            ).then(function () {
              // 成功
            }, function (err) {
              // 错误
            });
            $ionicLoading.hide();
          }, function (err) {
            alert(JSON.stringify(err));
            $ionicLoading.show({template: '下载失败！', noBackdrop: true, duration: 2000});
          }, function (progress) {
            //进度，这里使用文字显示下载百分比
            $timeout(function () {
              var downloadProgress = (progress.loaded / progress.total) * 100;
              $ionicLoading.show({
                template: "已经下载：" + Math.floor(downloadProgress) + "%"
              });
              if (downloadProgress > 99) {
                $ionicLoading.hide();
              }
            })
          });
        } else {
          // 取消更新
        }
      });
    };
    function showUpdateConfirm_ios(obj,num1,num2){
      var alertPopup = $ionicPopup.alert({
        title: '有新的版本:' + num1+' - '+num2,
        template: obj.gxnr, //从服务端获取更新的内容
        okText: '知道了'
      });
      alertPopup.then(function(res) {
        alert("Thank you for not eating my delicious ice cream cone");
      });
    };
  })
.factory('LS', ['$window', function($window) {
    return {
      set: function(key, value) {
        $window.localStorage[key] = value;
      },
      get: function(key, defaultValue) {
        return $window.localStorage[key] || defaultValue;
      },
      remove:function(key){
        return $window.localStorage.removeItem(key);
      },
      setObject: function(key, value) {
        $window.localStorage[key] = JSON.stringify(value);
      },
      getObject: function(key) {
        return JSON.parse($window.localStorage[key] || null);
      }
    }
  }])

